import { QueryExecutor } from '#src/database/core/QueryExecutor.js';
import { AppError } from '#src/common/errors/index.js';

export class BaseRepository {
    constructor(tableName, queries) {
        if (!tableName) throw new AppError('Table name is required for repository', 'REPOSITORY_ERROR');
        if (!queries || typeof queries !== 'object') throw new AppError('Queries object is required for repository', 'REPOSITORY_ERROR');
        this.tableName = tableName;
        this.queries = queries;
    }
    

    async execute(queryName, params, context = {}) {
        if (!this.queries[queryName]) {
            throw new AppError(`Query '${queryName}' not found in repository`, 'REPOSITORY_ERROR', { queryName, tableName: this.tableName });
        }
        return QueryExecutor.execute(this.queries[queryName], params, {
            ...context,
            tableName: this.tableName
        });
    }

    async executeTransaction(queryExecutions) {
        return QueryExecutor.executeTransaction(
            queryExecutions.map(({queryName, params, context}) => ({
                queryDef: this.queries[queryName],
                paramValues: params,
                context: {
                    ...context,
                    tableName: this.tableName
                }
            }))
        );
    }
}